package jdx_05_synchronized.jdx_04_银行账户加锁;

/*
(1).给写方法加锁
(2).给读方法加锁

和T1的代码一点没变，只是在读取的方法上加了锁

 */
public class T2 {
    String name;
    double balance;
    public synchronized void write(String name,double balance){
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.name = name;
        this.balance = balance;
    }
    public synchronized void read(){
        System.out.println(this.name+":"+this.balance);
    }

    public static void main(String[] args) {
        T2 t2 = new T2();
        //开启写操作线程
        new Thread(()->{
            t2.write("张三",100.0);
        }).start();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        t2.read();//第一次读取

        try {
            Thread.sleep(1200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t2.read();//第二次读取
    }

}
